package com.lp.controller;

import com.lp.bean.MenuInfo;
import com.lp.bean.MenuType;
import com.lp.bean.Meta;
import com.lp.bo.UserInfoBO;
import com.lp.cache.CacheName;
import com.lp.cache.ProCacheUtil;
import com.lp.common.Code;
import com.lp.common.Constants;
import com.lp.common.RequestURL;
import com.lp.util.ObjectUtil;
import com.lp.util.ResultMapUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletResponse;
import java.util.*;

@Controller
public class MenuInfoController extends BaseController {

    /**
     * 获取菜单列表
     * @param response
     * @param userKey
     * @param obj
     * @return
     */
    @RequestMapping(method = RequestMethod.POST, value = RequestURL.MenuInfo.MENU_INFO_LIST)
    public ModelAndView selectList(HttpServletResponse response,
                             @RequestHeader(value = ResultMapUtils.USER_KEY, required = true) String userKey ,
                             @RequestBody MenuInfo obj ) {
        Map<String, Object> resultMap = getResultMap();
        try {
            obj.setDelete_flag(Constants.DELETE.NO);
            List<MenuInfo> list = (List<MenuInfo>)getData(service.selectList("MenuInfo.selectList", obj));
            for (int i = 0; i < list.size(); i++) {
                MenuInfo menuInfo = list.get(i);
                Meta meta = new Meta();
                meta.setTitle(menuInfo.getTitle());
                meta.setHide(menuInfo.getHide());
                meta.setDisable(menuInfo.getDisable());
                meta.setKeepAlive(menuInfo.getKeepAlive());
                meta.setAffix(menuInfo.getAffix());
                meta.setLink(menuInfo.getLink());
                meta.setIframe(menuInfo.getIframe());
                meta.setIcon(menuInfo.getIcon());
                meta.setSort(menuInfo.getSort());
                menuInfo.setMeta(meta);
            }
            list = buildMenuTree(list);
            resultMap.put(PLAT_REPONSE_DATA, list);
        } catch (Exception e) {
            exception(e,resultMap, obj);
        }
        return getModelAndView(response, resultMap);
    }

    // 将查询到的所有菜单数据按pid递归构建树形结构
    public List<MenuInfo> buildMenuTree(List<MenuInfo> menuList) {
        Map<Integer, MenuInfo> menuMap = new HashMap<>();
        List<MenuInfo> rootMenus = new ArrayList<>();

        // 将菜单数据放入map，方便通过id查找菜单
        for (MenuInfo menu : menuList) {
            menuMap.put(menu.getId(), menu);
        }

        // 遍历菜单列表，构建树
        for (MenuInfo menu : menuList) {
            // 如果当前菜单的pid为0或者不存在，认为是根菜单
            if (menu.getPid() == 0) {
                rootMenus.add(menu);
            } else {
                // 查找父菜单，将当前菜单添加为子菜单
                MenuInfo parentMenu = menuMap.get(menu.getPid());
                if (parentMenu != null) {
                    parentMenu.addChild(menu);
                }
            }
        }

        return rootMenus;
    }

    /**
     * 添加菜单
     * @param response
     * @param userKey
     * @param obj
     * @return
     */
    @RequestMapping(method = RequestMethod.POST, value = RequestURL.MenuInfo.MENU_INFO)
    public ModelAndView save(HttpServletResponse response,
                             @RequestHeader(value = ResultMapUtils.USER_KEY, required = true) String userKey ,
                             @RequestBody MenuInfo obj ) {
        Map<String, Object> resultMap = getResultMap();
        try {
            UserInfoBO user = getUserInfoByUserKey(userKey);
            if(ObjectUtil.isNotEmpty(user)){
                obj.setAdd_id(user.getId());
                obj.setAdd_time(new Date());
                obj.setUpdate_time(new Date());
                resultMap = service.insert("MenuInfo.insert", obj);
                if(isOk(resultMap)){
                    // 添加菜单缓存
                    ProCacheUtil.addCache(CacheName.MENU_INFO, obj.getId().toString(), obj);
                    MenuType menuType = new MenuType();
                    menuType.setMenu_id(obj.getId());
                    menuType.setUser_type(Code.UserType.SUPER);
                    menuType.setUpdate_time(new Date());
                    service.insert("MenuType.insert", menuType);
                    if(isOk(resultMap)){
                        // 添加菜单角色缓存
                        ProCacheUtil.addCache(CacheName.MENU_TYPE, menuType.getId().toString(), menuType);
                    }
                }
            }else{
                putStatusCode(resultMap, Code.ResponseCode.SystemCode.NO_AUTHORIZATION);
            }
        } catch (Exception e) {
            exception(e,resultMap, obj);
        }
        return getModelAndView(response, resultMap);
    }

    /**
     * 编辑菜单
     * @param response
     * @param obj
     * @return
     */
    @RequestMapping(method = RequestMethod.PUT, value = RequestURL.MenuInfo.MENU_INFO)
    public ModelAndView update(HttpServletResponse response,
                               @RequestHeader(value = ResultMapUtils.USER_KEY, required = true) String userKey ,
                               @RequestBody MenuInfo obj ) {
        Map<String, Object> resultMap = getResultMap();
        try {
            resultMap = service.update("MenuInfo.update", obj) ;
            if(isOk(resultMap)){
                // 添加缓存
                ProCacheUtil.addCache(CacheName.MENU_INFO, obj.getId().toString(), obj);
            }
        } catch (Exception e) {
            exception(e,resultMap, obj);
        }
        return getModelAndView(response, resultMap);
    }

    /**
     * 删除菜单
     * @param response
     * @param userKey
     * @param id
     * @return
     */
    @RequestMapping(method = RequestMethod.DELETE, value = RequestURL.MenuInfo.MENU_INFO)
    public ModelAndView delete(HttpServletResponse response,
                               @RequestHeader(value = ResultMapUtils.USER_KEY, required = true) String userKey ,
                               @RequestParam Integer id ) {
        Map<String, Object> resultMap = getResultMap();
        try {
            MenuInfo obj = new MenuInfo();
            if (ObjectUtil.isEmpty(id)) {
                putStatusCode(resultMap, Code.ResponseCode.SystemCode.PARAM_ERROR);
            } else {
                obj.setId(id);
                obj.setDelete_flag(Constants.DELETE.YES);
                resultMap = service.update("MenuInfo.update", obj) ;
                if (isOk(resultMap)) {
                    ProCacheUtil.removeCache(CacheName.MENU_INFO, obj.getId().toString());
                    // 这边需要删除，所有的关联
                    MenuType menuType = new MenuType() ;
                    menuType.setMenu_id(id);
                    service.delete("MenuType.deleteByMenuId", menuType) ;
                }
            }
        } catch (Exception e) {
            exception(e,resultMap, id);
        }
        return getModelAndView(response, resultMap);
    }
}
